package com.atguigu.guli.service.ucenter.controller.api;


import com.atguigu.commonutils.JwtInfo;
import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.ResultCodeEnum;
import com.atguigu.commonutils.result.R;
import com.atguigu.guli.service.base.Exception.GuliException;
import com.atguigu.guli.service.base.dto.MemberDto;
import com.atguigu.guli.service.ucenter.entity.vo.LoginVo;
import com.atguigu.guli.service.ucenter.entity.vo.RegisterVo;
import com.atguigu.guli.service.ucenter.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author wangyang
 * @since 2021-06-13
 */
@CrossOrigin
@Api(tags = "会员管理")
@Slf4j
@RestController
@RequestMapping("/api/ucenter/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @ApiOperation("注册会员")
    @PostMapping("/register")
    public R register(
            @ApiParam(value = "会员信息",required = true)
            @RequestBody RegisterVo registerVo
            ) {
        memberService.register(registerVo);
        return R.ok();
    }

    @ApiOperation("会员登录")
    @PostMapping("/login")
    public R login(@RequestBody LoginVo loginVo) {

       String token = memberService.login(loginVo);
        return R.ok().data("token",token);
    }

    @ApiOperation("解析cookie中的JWT")
    @GetMapping("/get-login-info")
    public R getLoginInfo(HttpServletRequest request) {
        try {
            JwtInfo jwtInfo = JwtUtils.getMemberIdByJwtToken(request);
            return R.ok().data("userInfo",jwtInfo);
        } catch (Exception e) {
            log.error("解析用户信息失败，" + e.getMessage());
            throw new GuliException(ResultCodeEnum.FETCH_USERINFO_ERROR);
        }
    }

    @GetMapping("/inner/get-member-dto/{memberId}")
   public MemberDto getMemberDtoByMemberId(@PathVariable(value = "memberId") String memberId){
      return  memberService.getMemberDtoByMemberId(memberId);
    }
}

